<?php
/**
 * 【司机完善资料】
 * Created by PhpStorm.
 * User: 孙凯
 * Date: 2018-06-11
 * Time: 10:55
 */

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\User;
use Illuminate\Contracts\Validation\Validator;

class ChauffeurController extends BaseController
{
    /**生成token
     * @return mixed
     */
    public function test()
    {
        $user = User::where('id', 1)->select('id')->first();
        return JWTAuth::fromUser($user);
    }

    /**
     * [司机完善资料首页接口]
     * @Author sk
     * @DateTime 2018-06-11
     * @version
     * @param Request $request
     * @return array
     */
    public function addpost(Request $request)
    {
        try {
            $arr = (JWTAuth::parseToken()->authenticate());
            $arr = json_decode($arr, true);
            $id = $arr['id'];
            $file = $request->all();
            if (empty($file['driver_name']) || empty($file['age']) || empty($file['sex']) || empty($file['driver_phone']) || empty($file['home_address']) || empty($file['contact']) || empty($file['contact_phone']) || empty($file['condition']) || empty($file['examination_time']) || empty($file['previous_history']) || empty($file['pin_codes']) || empty($file['licenseId_type']) || empty($file['licenseId_old'])
            ) {
                return '参数请填写完整';
            }
            $data = [
                'driver_name' => $file['driver_name'],//姓名
                'age' => $file['age'],//年龄
                'sex' => $file['sex'],//性别 1男2女
                'driver_phone' => $file['driver_phone'],//手机号
                'home_address' => $file['home_address'],//家庭住址
                'contact' => $file['contact'],//紧急联系人
                'contact_phone' => $file['contact_phone'],//紧急联系人电话
                'condition' => $file['condition'],//健康状况
                'examination_time' => $file['examination_time'],//上次体检时间
                'previous_history' => $file['previous_history'],//既往病史
                'pin_codes' => $file['pin_codes'],//身份证号码
                'licenseId_type' => $file['licenseId_type'],//驾驶证类型
                'licenseId_old' => $file['licenseId_old'],//驾龄
            ];
            if ($arr['account_status'] == 2) {
                $fromDate = DB::table('driver')->where('id', $id)->update($data);
                $fromDate = json_decode(json_encode($fromDate), true);
                return response(['msg' => $fromDate, 'code' => '1000', 'message' => '资料提交成功等待审核']);
            } else {
                return response(['msg' => '', 'code' => '1001', 'message' => '您已经通过审核']);
            }
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => '1011', 'message' => '非法的token']);
        }
    }

    /**
     * 【司机--上传头像】
     * @Author sk
     * @param Request $request
     * @return string
     * @throws JWTException
     */
    public function uploadPhoto(Request $request)
    {
        try {
            $user = (JWTAuth::parseToken()->authenticate());
            $user = json_decode($user, true);
            $id = $user['id'];
            $file = $request->file('user_pic');

            //return $file;
            if ($file) {
                $file_path = 'uploads/' . date("Ym") . "/";
                $extension = $file->getClientOriginalExtension();//上传文件的后缀.
                $file_name = md5(time() . mt_rand(10, 99)) . '.' . $extension;
                $info = $file->move($file_path, $file_name);
                // return $info;
                if (!$info) {
                    $error = $file->getError();
                    return response(['msg' => $error, 'code' => '1011', 'message' => '图片保存到本地失败']);
                }
                $data['user_pic'] = $file_path . $file_name;
                $re = DB::table('driver')->where('id', $id)->update(['user_pic' => $data['user_pic']]);

                if ($re) {
                    $fromData = [
                        'code' => '1000',
                        'data' => $data['user_pic']
                    ];
                    $data = json_decode(json_encode($fromData), true);
                    return response(['msg' => $data, 'code' => '1000', 'message' => '图片上传成功']);
                } else {
                    return response(['msg' => '', 'code' => '1012', 'message' => '图片保存到数据库失败']);
                }
            } else {
                return response(['msg' => '', 'code' => '1011', 'message' => '获取图片失败']);
            }
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => '1007', 'message' => '非法token']);
        }

    }

    /**
     * 【身份证上传】
     * @param Request $request
     * @return mixed
     */
    public function upload(Request $request)
    {
        $user = (JWTAuth::parseToken()->authenticate());
        $user = json_decode($user, true);
        $id = $user['id'];
        $file = $request->allFiles();
        if (empty($file)) {
            exit("需要上传2张图片，请重试！");
        }
        $filePath = [];  // 定义空数组用来存放图片路径
        foreach ($file as $key => $value) {
            // 判断图片上传中是否出错
            if (!$value->isValid()) {
                exit("上传图片出错，请重试！");
            }
            if (!empty($value)) {//此处防止没有多文件上传的情况
                $allowed_extensions = ["png", "jpg", "jpeg"];
                if ($value->getClientOriginalExtension() && !in_array($value->getClientOriginalExtension(), $allowed_extensions)) {
                    exit('您只能上传PNG、jpg.jpeg！');
                }
                $destinationPath = '/uploads/' . date('Y-m-d'); // public文件夹下面uploads/xxxx-xx-xx 建文件夹
                $extension = $value->getClientOriginalExtension();   // 上传文件后缀
                $fileName = date('YmdHis') . mt_rand(100, 999) . '.' . $extension; // 重命名
                $value->move(public_path() . $destinationPath, $fileName); // 保存图片
                //return $dd;
                $filePath[] = $destinationPath . '/' . $fileName;
            }
        }
// 返回上传图片路径，用于保存到数据库中
        if (empty($filePath['0']) || empty($filePath['1'])){
            return response(['msg' => '', 'code' => '1011', 'message' => '图片保存到数据库失败，请确定上传2张图片？']);
        }
         DB::table('driver')->where('id', $id)->update([
            'pin_pic' => $filePath['0'],
            'pinf_pic' => $filePath['1']
        ]);
        if (!empty($filePath['0']) && !empty($filePath['1'])) {
            $fromData = [
                'code' => '1000',
                'data' => $filePath
            ];
            $fromData = json_decode(json_encode($fromData), true);
            return response(['msg' => $fromData, 'message' => '图片上传成功']);
        } else {
            return response(['msg' => '', 'code' => '1011', 'message' => '图片保存到数据库失败，请确定上传2张图片？']);
        }
    }

}